package SystemControl;


import java.util.ArrayList;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;

import VirtualMachines.ECU;

import Communication.ECUManager;
import Communication.MesureDistanceSensorManager;
import Communication.ReceiveSensorManager;
import Communication.SendSensorManager;
import Communication.UIPanelManager;
import Data.CarDataModel;

public class CommunicationManager {

	private Handler confirmHandler = new Handler() {
		@Override
		public void close() throws SecurityException {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			collectDataFromManagers();
		}
		@Override
		public void flush() {
		}
		@Override
		public void publish(LogRecord arg0) {
		}
	};
	
	private ECUManager ecuMgr;
	private MesureDistanceSensorManager mdsMgr;
	private ReceiveSensorManager rcvSensorMgr;
	private static SendSensorManager sendSensorMgr;
	private UIPanelManager uiPanelMgr;
	
	public static List<CarDataModel> cars;
	static CarDataModel currentCar;
	boolean isStart;
	
	public CommunicationManager(){
		ecuMgr = new ECUManager();
		mdsMgr = new MesureDistanceSensorManager();
		rcvSensorMgr = new ReceiveSensorManager();
		sendSensorMgr = new SendSensorManager();
		uiPanelMgr = new UIPanelManager();
		
		cars = new ArrayList<CarDataModel>();
		isStart = true;
		
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				// TODO Auto-generated method stub
				ECUManager.setCurrentVeloctiy();
				MesureDistanceSensorManager.setCurrentDistance();
				ReceiveSensorManager.setDataOfFrontCar();
				confirmHandler.close();
			}
		}).start();
	}
	
	public static List<CarDataModel> collectDataFromManagers(){
		currentCar = new CarDataModel();
		currentCar.distanceToFront = MesureDistanceSensorManager.getCurrentDistance();
		currentCar.velocity = ECUManager.getCurrentVeloctiy();
		
		try{
			cars = new ArrayList<CarDataModel>();
			List<CarDataModel> carsData = ReceiveSensorManager.getDataOfFrontCar();
			
			for(int i = 0; i < 2; i++){
				cars.add(carsData.get(i));
			}
			cars.add(currentCar);
		}
		catch (Exception e) {
			// TODO: handle exception
		}
		
		sendDataToSendSensor();
		return cars;
	}
	
	private static void sendDataToSendSensor(){
		sendSensorMgr.setDataForSending(cars);
	}
	
	public static void sendSignalToECU(boolean signal){
		ECU.signal(signal);
	}
}
